import { getUserRole } from "../../api/login";
import {defaultRouterMap,asyncRouterMap} from '../../router'

export default {
  namespaced: true,
  state: {
    roles: [],
    addRoutes: [],
    allRoutes: defaultRouterMap
  },
  getters: {
    roles: state => state.roles,
    allRoutes: state => state.allRoutes, // 所有的
    addRoutes: state => state.addRoutes // 匹配的
  },
  mutations: {
    SET_ROLES(state, value) {
      state.roles = value;
    },
    SET_ROUTER(state, router) {
      state.addRoutes = router
      state.allRoutes = defaultRouterMap.concat(router);
    }
  },
  actions: {
    getRoles({ commit }, request) {
      return new Promise((resolve, reject) => {
        getUserRole().then(res => {
          commit(`SET_ROLES`, res);
          resolve(res);
        });
      });
    },
    createRouter({ commit }, data) {
      return new Promise((resolve, reject) => {
        const role = data;
        let addRoutes = [];
        if (role.includes("admin")) {
          addRoutes = asyncRouterMap;
        } else {
          addRoutes = asyncRouterMap.filter(item => {
            if (role.includes(item.meta.system)) {
              return item;
            }
          });
        }
        commit(`SET_ROUTER`, addRoutes);
        resolve(addRoutes);
      });
    }
  }
};
